package cc.SSM.utils;

import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by rongmc on 16/6/1.
 */
public class CookieUtil {




    private  static Cookie getCookie(HttpServletRequest httpServletRequest,String name){
        Cookie[] cookies =  httpServletRequest.getCookies();
        Cookie cookie = WebUtils.getCookie(httpServletRequest,name);
        return cookie ;
    }

    public static String getCookieValue(HttpServletRequest httpServletRequest,String name){
        Cookie cookie = getCookie(httpServletRequest,name);
        if(cookie!=null){
            return cookie.getValue();
        }
        return "";
    }

    public static String getCookieDomain(HttpServletRequest httpServletRequest,String name){
        Cookie cookie = getCookie(httpServletRequest,name);
        return cookie.getDomain() ;
    }

    public static Integer getCookieMaxAge(HttpServletRequest httpServletRequest,String name){
        Cookie cookie = getCookie(httpServletRequest,name);
        return cookie.getMaxAge();
    }

    public static String getCookiePath(HttpServletRequest httpServletRequest,String name){
        Cookie cookie = getCookie(httpServletRequest,name);
        return  cookie.getPath();
    }

    public static String getCookieComment(HttpServletRequest httpServletRequest,String name){
        Cookie cookie = getCookie(httpServletRequest,name);
        return cookie.getComment();
    }

    public static void setCookie(HttpServletResponse httpServletResponse,String name,String value,String domain,Integer maxAge){
        Cookie cookie = new Cookie(name,value);
        cookie.setDomain(domain);
        cookie.setPath("/");//如果不设置path则只有当前path生效
        cookie.setMaxAge(maxAge);
        httpServletResponse.addCookie(cookie);
    }

    public static void setCookie(HttpServletResponse httpServletResponse,String name,String value){
        setCookie(httpServletResponse,name,value,"",3600);
    }

    public  static void removeCookie(HttpServletResponse httpServletResponse,String domain,String name){
        Cookie cookie = new Cookie(name,"");
        cookie.setDomain(domain);
        cookie.setPath("/");//如果不设置path则只有当前path生效
        cookie.setMaxAge(0);
        httpServletResponse.addCookie(cookie);
    }

}
